package server.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;


public class DemoServerHandler implements Runnable {
	private Socket clientSocket;
	private InputStream is = null;
	private boolean isStop = false;

	public DemoServerHandler(Socket clientSocket) {
		this.clientSocket = clientSocket;
	}

	@Override
	public void run() {
		while (!isStop) {
			decode();
		}
	}

	private String decode() {
		if (is == null) {
			try {
				is = clientSocket.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
				isStop = true;
			}
		}
		String value;
		byte[] btLength = read(is, 4);
		if (btLength == null) {
			return null;
		}
		int length = ByteBuffer.wrap(btLength).getInt();
		btLength = null;
		byte[] data = read(is, length);
		if (data == null) {
			return null;
		}
		value = new String(data);
		return value;
	}
	
	private byte[] read(InputStream is, int length){
//		ByteBuffer bb = ByteBuffer.allocate(length);
		byte[] allbt = new byte[length];
//		byte[] zxc = allbt.clone();
//		bb.clear();
//		bb.position(0);
		if (is == null) {
			return null;
		}
		int realRead = 0;
		int totalRead = 0;
//		int position = 0;
		byte[] bt = null;//new byte[0];
//		int i = 0;
		try {
//			logE.debug("Start read==>totalRead: " + totalRead + "|length: " + length + " | " + i);
			while(totalRead < length) {
				bt = new byte[length - totalRead];
				realRead = is.read(bt);
				if (realRead < 0) {
//					logE.debug("break read==>totalRead: " + totalRead + "|length: " + length + " | " + i);
					return null;
				}
//				bb.put(bt, 0, realRead);
				System.arraycopy(bt, 0, allbt, totalRead, realRead);
				totalRead += realRead;
				
//				i++;
			
//				logE.debug("totalRead: " + totalRead + "|length: " + length + " | " + i);
			}
		} catch (Exception e) {
			e.printStackTrace();
			isStop = true;
		}
		
//		bb.position(0);
//		bb.rewind();
//		bt = bb.array();
//		bb.clear();
//		bb = null;
		freeMemory();
		return allbt;
	}
	
	private void freeMemory(){
		Runtime rt = Runtime.getRuntime();
		rt.gc();
	}

}
